﻿using AspNetCoreRateLimit;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using RuoVea.ExConfig;
using System;

namespace RuoVea.ExWeb.IPLimit
{
    /// <summary>
    /// IPLimit限流 启动服务
    /// </summary>
    public static class IPLimitIOptions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        public static void IpLimitSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            // needed to store rate limit counters and ip rules
            services.AddMemoryCache();
            //load general configuration from appsettings.json
            services.Configure<IpRateLimitOptions>(Appsettings.GetSection("IPLimit"));

            ////注入计数器和规则存储 inject counter and rules stores inject counter and rules distributed cache stores
            services.AddSingleton<IIpPolicyStore, MemoryCacheIpPolicyStore>();
            services.AddSingleton<IRateLimitCounterStore, MemoryCacheRateLimitCounterStore>();

            // the clientId/clientIp resolvers use it.
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            // 配置（计数器密钥生成器） configuration (resolvers, counter key builders)
            services.AddSingleton<IRateLimitConfiguration, RateLimitConfiguration>();
        }

        /// <summary>
        /// app 设置
        /// </summary>
        /// <param name="app"></param>
        public static void UseMiddleware(this IApplicationBuilder app)
        {
            app.UseMiddleware<IPLimitMiddleware>();
        }

    }
}
